# -*- coding: utf-8 -*-
"""
@Time    : 2022/7/25 18:07
@Author  : Corey
"""
from gui.driver.map_gui import MapGui
from PyQt5.QtCore import Qt, QPoint, pyqtSignal
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QApplication, QMenu, QAction, QFileDialog, QMessageBox, QTableWidgetItem
import csv
import sys


class MapAction(MapGui):
    test_ingore_list = pyqtSignal(list,list)
    movePos = pyqtSignal(list)

    def __init__(self):
        super(MapAction, self).__init__()
        self.subdie_list = []
        self.item_list = []
        self.die_count = 0
        self._bind_actions()

    def _bind_actions(self):
        self.tw_content.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tw_content.customContextMenuRequested[QPoint].connect(self.right_menu)
        self.pb_verify.clicked.connect(self._verify_test)

    def _refresh_ui_display(self, die_count, subdie_list):
        self.tw_content.clear()
        self.subdie_list = subdie_list
        self.die_count = die_count
        self.tw_content.setColumnCount(len(self.subdie_list))
        self.tw_content.setRowCount(self.die_count)
        self.tw_content.setHorizontalHeaderLabels([f"SubDie {subdie_id}" for subdie_id in self.subdie_list])
        vhead_list = [f"Die {die_id}" for die_id in range(1, self.die_count + 1)]
        self.tw_content.setVerticalHeaderLabels(vhead_list)
        for die_id in range(self.die_count):
            for subdie_id in range(len(self.subdie_list)):
                tb_item = QTableWidgetItem()
                tb_item.setCheckState(Qt.Checked)
                self.tw_content.setItem(die_id, subdie_id, tb_item)
        self.showMaximized()

    def _verify_test(self):
        reply = QMessageBox.question(self, "信息提示", "是否关闭此页面并开始测试?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)

        if reply == QMessageBox.Yes:
            test_list,ignore_list = self._get_test_ignore_list()
            self.test_ingore_list.emit(test_list,ignore_list)
            self.hide()

    def right_menu(self, event):
        menu = QMenu()
        menu.addAction("选中全部")
        menu.addAction("取消全部")
        menu.addAction("选中当前")
        menu.addAction("取消当前")
        menu.addAction("查看忽略数量")
        menu.addAction("移动到当前位置")
        menu.addAction("导入批量操作文件")
        menu.addAction("导出批量操作文件")
        menu.triggered[QAction].connect(self.processtrigger)
        menu.exec_(QCursor.pos())

    def processtrigger(self, q):
        if q.text() == "导入批量操作文件":
            fileName, fileType = QFileDialog.getOpenFileName(self, "选取文件", "./static/wafer_list",
                                                             "subdie ignore Files(*.csv)")
            if fileName.strip() == "":
                return
            with open(fileName, "r") as fp:
                content_list = list(csv.reader(fp))[1:]
                for group in content_list:
                    self.tw_content.item(int(group[0]) - 1, self.subdie_list.index(int(group[1]))).setCheckState(0)
        elif q.text() == "导出批量操作文件":
            fileName, ok = QFileDialog.getSaveFileName(self,
                                                       "设置保存",
                                                       "./static/wafer_list",
                                                       "subdie ignore Files(*.csv)")
            if fileName.strip() == "":
                return
            with open(fileName, "w", newline="") as fp:
                writer = csv.writer(fp)
                writer.writerow(["Die", "SubDie"])
                ignore_id_list = self._get_ignore_list()
                for target_list in ignore_id_list:
                    writer.writerow(target_list)

        elif q.text() == "选中当前":
            item_list = self.tw_content.selectedItems()
            for item in item_list:
                item.setCheckState(2)
        elif q.text() == "取消当前":
            item_list = self.tw_content.selectedItems()
            for item in item_list:
                item.setCheckState(0)

        elif q.text() == "选中全部":
            for row in range(self.tw_content.rowCount()):
                for col in range(self.tw_content.columnCount()):
                    self.tw_content.item(row, col).setCheckState(2)
        elif q.text() == "取消全部":
            for row in range(self.tw_content.rowCount()):
                for col in range(self.tw_content.columnCount()):
                    self.tw_content.item(row, col).setCheckState(0)
        elif q.text() == "移动到当前位置":
            self.movePos.emit([self.tw_content.currentRow() + 1, self.subdie_list[self.tw_content.currentColumn()]])

        elif q.text() == "查看忽略数量":
            test_list,ignore_list = self._get_test_ignore_list()
            content = f"一共忽略{len(ignore_list)}个测试项\n"
            QMessageBox.information(self, "信息提示", content)

    def _get_test_ignore_list(self):
        test_list = []
        ignore_list = []
        for row in range(self.tw_content.rowCount()):
            for col in range(self.tw_content.columnCount()):
                if self.tw_content.item(row, col).checkState() == 0:
                    ignore_list.append([row + 1, self.subdie_list[col]])
                else:
                    test_list.append([row + 1, self.subdie_list[col]])
        return test_list, ignore_list


if __name__ == '__main__':
    app = QApplication(sys.argv)
    wd_obj = MapAction()
    # wd_obj._refresh_ui_display(60, [0, 1, 2, 3])
    subdie_list = [i for i in range(1, 19)]
    wd_obj._refresh_ui_display(26, subdie_list)
    wd_obj.show()
    sys.exit(app.exec_())
